import Taro from '@tarojs/taro'
import qs from 'kuan-utils/lib/qs'
import router from '@/router'

// const defaultAddress = {
//   adcode: 310100,
//   city: '上海市',
//   district: '静安区',
//   nation: '中国',
//   province: '上海市'
// }

const defaultAddress = {
  currentCode: 320500,
  currentCity: '苏州'
}

function getLocation() {
  return new Promise((resolve, reject) => {
    const s = document.createElement('script')
    window.getCurrentLocation = ({ status, result }) => {
      if (status) {
        reject(result)
      } else {
        const info = result.ad_info
        info.adcode = Math.floor(info.adcode / 100) * 100
        if (info.adcode === 310000) info.adcode = 310100
        if (info.adcode === 320000) info.adcode = 320500

        resolve({
          currentCode: info.adcode,
          currentCity: info.city
        })
      }
    }
    s.src =
      'https://apis.map.qq.com/ws/location/v1/ip?key=DJ2BZ-Z26HI-64QGE-5EY65-UQ6KS-BTFXM&callback=getCurrentLocation&output=jsonp'
    document.body.appendChild(s)
    document.body.removeChild(s)
  })
}

const delay = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(defaultAddress)
    }, 5000)
  })
}

export default {
  async get() {
    Taro.showLoading()
    try {
      const location = await Promise.race([getLocation(), delay()])
      Taro.hideLoading()
      return location
    } catch (e) {
      Taro.hideLoading()
      return Promise.reject(defaultAddress)
    }
  }
}
